require 'digest/sha2'

class UsersController < ApplicationController
  def initalize
    #@errors = {}
  end

  def new
  end

  def show
    return unless params[:id] == "validate"
    error = false
    classes = false
    user = nil

    if params[:s] and params[:u] and params[:p]
      seeds = nil
      if (seeds = Seed.all(s: params[:s])).length == 1
        if (users = User.all(un: params[:u])).length == 1
          if validate_password users[0], params[:p], params[:s]
            user = users[0]
            c = user.user_lang
            unless c.length == 0
              classes = []
              c.each do |h|
                classes << {la: h.la, cl: h.cl}
              end
              seeds[0].destroy
            else
              error = "You're not signed up for any classes. Soon you'll be able to choose one from here but for now please use your control panel."
            end
          else
            error = "Invalid username or password."
          end
        else
          error = "Invalid username or password."
        end
      else
        error = "Server error. Please try reloading the page or file a bug report if this persists."
        #@errors[request.remote_ip] ||= []
        #@errors[request.remote_ip] << "Not enough/too many seeds (number found: #{seeds}) @#{Time.now.to_s}" #TODO: Include debugging info
      end
    else
      error = "Server error. Please try reloading the page or file a bug report if this persists."
      #@errors[request.remote_ip] ||= []
      #@errors[request.remote_ip] << "Not enough parameters @#{Time.now.to_s}" #TODO: Include debugging info
    end

    json = { e: error }
    if user
      json[:c] = classes
      json[:u] = user.un
      json[:r] = user.rn
    end
    
    respond_to do |format|
      format.json { render json: json }
    end
  end

  private

  def validate_password user, password, seed
    if Digest::SHA2.hexdigest(user.pw + seed) == password
      true
    else
      false
    end
  end

end
